<template>
	<view class="main">
		<view class="icon" :class="{ran:status}" @click="stateChange">
			<image class="img" :src="require('./disk-cd.png')" mode="widthFix" :style="style"></image>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'music',
		data() {
			return {
				audioCtx: {},
				status: false,
			}
		},
		props: {
			size: {
				default: 80,
				type: [Number, String]
			},
			autoplay: {
				default: true,
				type: Boolean
			},
			musicSrc: {
				default: '',
				type: String,

			}
		},
		watch: {
			musicSrc(newVal) {
				this.musicSrc = newVal
				this.$nextTick()
					.then(res => {
						this.audioCtx.src = newVal
						this.playAudio()
					})
			}
		},
		computed: {
			style() {
				var size = this.size;
				var style = `width:${size}px;height:${size}px;`;
				return style
			}
		},
		created() {
			var _this = this
			this.audioCtx = uni.createInnerAudioContext()
			this.audioCtx.loop = true
			// 音频播放事件 
			this.audioCtx.onPlay(() => {
				_this.status = true
				_this.$emit('onStateChange', "play")

			})
			// 音频暂停事件
			this.audioCtx.onPause(() => {
				_this.status = false
				_this.$emit('onStateChange', "pause")
			})
			// 异常
			this.audioCtx.onError(err => {
				console.log(err)
			})
			// 音频进度更新事件
			this.audioCtx.onTimeUpdate(() => {
				_this.$emit('onTimeUpdate', this.audioCtx.currentTime)
			})

			if (this.musicSrc) {
				this.audioCtx.src = this.musicSrc
			}
		},
		beforeDestroy() {
			this.pauseAudio()
			this.audioCtx.destroy()
			this.audioCtx = null
		},
		methods: {
			playAudio() {
				this.audioCtx.play()
			},
			pauseAudio() {
				this.audioCtx.pause()
			},
			seekAudioTo(time) {
				this.audioCtx.seek(time)
			},
			stateChange() {
				const status = this.status
				if (status) {
					this.pauseAudio()
				} else {
					this.playAudio()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.ran {
		.img {
			animation: turn 1s linear infinite;
		}
	}

	@keyframes turn {
		0% {
			-webkit-transform: rotate(0deg);
		}

		25% {
			-webkit-transform: rotate(90deg);
		}

		50% {
			-webkit-transform: rotate(180deg);
		}

		75% {
			-webkit-transform: rotate(270deg);
		}

		100% {
			-webkit-transform: rotate(360deg);
		}
	}
</style>
